home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 19 advanced win32 techniques / encryptorservice / encryptor.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  7.8 KB  |  216 lines

  1. Imports System.ServiceProcess
  2.  
  3. Public Class Encryptor
  4.     Inherits System.ServiceProcess.ServiceBase
  5.  
  6. #Region " Component Designer generated code "
  7.  
  8.     Public Sub New()
  9.         MyBase.New()
  10.  
  11.         ' This call is required by the Component Designer.
  12.         InitializeComponent()
  13.  
  14.         ' Add any initialization after the InitializeComponent() call
  15.  
  16.     End Sub
  17.  
  18.     ' The main entry point for the process
  19.     Shared Sub Main()
  20.         Dim ServicesToRun() As System.ServiceProcess.ServiceBase
  21.  
  22.         ' More than one NT Service may run within the same process. To add
  23.         ' another service to this process, change the following line to
  24.         ' create a second service object. For example,
  25.         '
  26.         '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
  27.         '
  28.         ServicesToRun = New System.ServiceProcess.ServiceBase() {New Encryptor()}
  29.  
  30.         System.ServiceProcess.ServiceBase.Run(ServicesToRun)
  31.     End Sub
  32.     Friend WithEvents FileSystemWatcher1 As System.IO.FileSystemWatcher
  33.  
  34.     'Required by the Component Designer
  35.     Private components As System.ComponentModel.Container
  36.  
  37.     ' NOTE: The following procedure is required by the Component Designer
  38.     ' It can be modified using the Component Designer.  
  39.     ' Do not modify it using the code editor.
  40.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  41.         Me.FileSystemWatcher1 = New System.IO.FileSystemWatcher()
  42.         CType(Me.FileSystemWatcher1, System.ComponentModel.ISupportInitialize).BeginInit()
  43.         '
  44.         'FileSystemWatcher1
  45.         '
  46.         Me.FileSystemWatcher1.NotifyFilter = ((System.IO.NotifyFilters.FileName Or System.IO.NotifyFilters.DirectoryName) _
  47.                     Or System.IO.NotifyFilters.LastWrite)
  48.         '
  49.         'Encryptor
  50.         '
  51.         Me.CanPauseAndContinue = True
  52.         Me.ServiceName = "Encryptor"
  53.         CType(Me.FileSystemWatcher1, System.ComponentModel.ISupportInitialize).EndInit()
  54.  
  55.     End Sub
  56.  
  57. #End Region
  58.  
  59.     ' The path of the watched directory.
  60.     ' IMPORTANT: create this directory if it doesn't exist
  61.  
  62.     Dim Path As String = "C:\Encrypt"
  63.  
  64.     ' the service has been started
  65.  
  66.     Protected Overrides Sub OnStart(ByVal args() As String)
  67.         If args.Length > 0 Then
  68.             Path = args(0)
  69.             Me.EventLog.WriteEntry(Path)
  70.         End If
  71.         ' Ensure that the directory exists.
  72.         If Not System.IO.Directory.Exists(Path) Then
  73.             System.IO.Directory.CreateDirectory(Path)
  74.         End If
  75.         ' Start receiving file events.
  76.         FileSystemWatcher1.Path = Path
  77.         FileSystemWatcher1.EnableRaisingEvents = True
  78.     End Sub
  79.  
  80.     ' the service has been stopped, paused, or resumed
  81.  
  82.     Protected Overrides Sub OnStop()
  83.         ' Stop receiving file events.
  84.         FileSystemWatcher1.EnableRaisingEvents = False
  85.     End Sub
  86.  
  87.     Protected Overrides Sub OnPause()
  88.         ' Stop receiving file events.
  89.         FileSystemWatcher1.EnableRaisingEvents = False
  90.     End Sub
  91.  
  92.     Protected Overrides Sub OnContinue()
  93.         ' Start receiving file events.
  94.         FileSystemWatcher1.EnableRaisingEvents = True
  95.     End Sub
  96.  
  97.  
  98.     ' This is the binary password.
  99.     Dim pwBytes() As Byte = {123, 234, 12, 9, 78, 89, 212}
  100.     ' This is the extension used for temporary files.
  101.     Dim tempExt As String = ".$$$"
  102.  
  103.     Private Sub FileSystemWatcher1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created
  104.         ' Ignore temporary files created by the encryption process.
  105.         If System.IO.Path.GetExtension(e.FullPath) = tempExt Then Exit Sub
  106.  
  107.         Do
  108.             Try
  109.                 ' Encrypt the file being created.
  110.                 EncryptFile(e.FullPath, pwBytes)
  111.                 ' Exit if successful
  112.                 Exit Do
  113.             Catch ex As Exception
  114.                 Dim attempts As Integer
  115.                 attempts += 1
  116.                 ' Make up to 10 attempts.
  117.                 If attempts > 10 Then Exit Sub
  118.                 ' Wait for a while and retry the operation.
  119.                 System.Threading.Thread.Sleep(1000)
  120.             End Try
  121.         Loop
  122.  
  123.     End Sub
  124.  
  125.     ' This is the encryption/decryption routine
  126.  
  127.     Private Sub EncryptFile(ByVal Filename As String, ByVal pwBytes() As Byte)
  128.         ' This the the size of each input block.
  129.         ' (Files must be decrypted using the same block size.)
  130.         Const BLOCKSIZE = 8192
  131.  
  132.         ' Determine the name of the temporary file.
  133.         Dim tempFile As String = Filename & tempExt
  134.  
  135.         ' Open the source file as a binary input stream.
  136.         Dim inStream As New System.IO.FileStream(Filename, IO.FileMode.Open)
  137.         ' Open the output temporary file as a binary input stream.
  138.         Dim outStream As New System.IO.FileStream(tempFile, IO.FileMode.Create)
  139.         ' Determine the number of bytes to read.
  140.         Dim bytesLeft As Long = inStream.Length
  141.         ' Prepare an input buffer.
  142.         Dim buffer(BLOCKSIZE - 1) As Byte
  143.  
  144.         ' Loop until there are bytes to read.
  145.         Do While bytesLeft > 0
  146.             ' Read max 8K bytes at a time
  147.             Dim bytesToRead As Long = Math.Min(BLOCKSIZE, bytesLeft)
  148.             ' Read into the input buffer.
  149.             inStream.Read(buffer, 0, bytesToRead)
  150.             ' Encrypt this buffer.
  151.             EncryptArray(buffer, pwBytes)
  152.             ' Output to the temporary file.
  153.             outStream.Write(buffer, 0, bytesToRead)
  154.             ' We have fewer bytes to read now
  155.             bytesLeft -= bytesToRead
  156.         Loop
  157.  
  158.         ' Close the two streams.
  159.         inStream.Close()
  160.         outStream.Close()
  161.         ' Delete the source file.
  162.         System.IO.File.Delete(Filename)
  163.         ' Rename the temporary file as the original file.
  164.         System.IO.File.Move(tempFile, Filename)
  165.     End Sub
  166.  
  167.     ' This routine encrypts an array of bytes.
  168.     Sub EncryptArray(ByVal buffer() As Byte, ByVal pwBytes() As Byte)
  169.         ' This index points to the buffer.
  170.         Dim index As Integer
  171.         ' This index points to the password array.
  172.         Dim i As Integer
  173.         ' The max value for i.
  174.         Dim maxval As Integer = pwBytes.Length
  175.  
  176.         For index = 0 To buffer.Length - 1
  177.             ' XOR each element in the buffer with the corresponding p
  178.             buffer(index) = buffer(index) Xor pwBytes(i)
  179.             ' ensure that the index is always in the valid range.
  180.             i = (i + 1) Mod maxval
  181.         Next
  182.     End Sub
  183.  
  184.     ' This method is called only if the CanShutdown property is True.
  185.  
  186.     Protected Overrides Sub OnShutdown()
  187.         ' Add here the code to execute when the system shuts down
  188.     End Sub
  189.  
  190.     ' This method is called only if the CanHandlePowerEvent property is True.
  191.  
  192.     Protected Overrides Function OnPowerEvent(ByVal powerStatus As System.ServiceProcess.PowerBroadcastStatus) As Boolean
  193.         Select Case powerStatus
  194.             Case PowerBroadcastStatus.Suspend
  195.                 ' Add here the code to execute when the system enters suspend mode.
  196.             Case PowerBroadcastStatus.ResumeSuspend
  197.                 ' Add here the code to execute when the system exits suspend mode.
  198.             Case PowerBroadcastStatus.BatteryLow
  199.                 ' Add here the code to execute when batteries are low.
  200.         End Select
  201.         ' This method must return True.
  202.         Return True
  203.     End Function
  204.  
  205.     ' This method is called when a custom command is sent to the service.
  206.  
  207.     Protected Overrides Sub OnCustomCommand(ByVal command As Integer)
  208.         Select Case command
  209.             Case 1
  210.                 ' React to custom command #1
  211.             Case 2
  212.                 ' React to custom command #1
  213.         End Select
  214.     End Sub
  215. End Class
  216.